#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
跨平台文件选择器服务
提供Web API接口用于文件选择操作
"""

import os
import sys
import json
import subprocess
import platform
import tempfile
import mimetypes
from pathlib import Path
from typing import List, Dict, Any, Optional, Union

from flask import Flask, request, jsonify, send_file
from flask_cors import CORS


class CrossPlatformFileSelector:
    """跨平台文件选择器"""
    
    def __init__(self):
        self.platform = platform.system()
        self.script_path = Path(__file__).parent / "file_selector_script.py"
        
        # 检查脚本文件是否存在
        if not self.script_path.exists():
            raise FileNotFoundError(f"文件选择器脚本不存在: {self.script_path}")
    
    def select_files(self, multiple: bool = False, file_types: Optional[List[Dict]] = None, 
                    title: str = "选择文件", initial_dir: Optional[str] = None) -> Dict[str, Any]:
        """选择文件"""
        try:
            # 构建命令参数
            cmd = [sys.executable, str(self.script_path)]
            
            if multiple:
                cmd.append('--multiple')
            
            if file_types:
                # 使用JSON格式传递文件类型过滤器
                cmd.extend(['--file-types-json', json.dumps(file_types)])
            
            cmd.extend(['--title', title])
            
            if initial_dir:
                cmd.extend(['--initial-dir', initial_dir])
            
            # 执行脚本
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=300,  # 5分钟超时
                encoding='utf-8'
            )
            
            if result.returncode == 0:
                try:
                    output = json.loads(result.stdout.strip())
                    return {
                        "success": True,
                        "data": output,
                        "platform": self.platform
                    }
                except json.JSONDecodeError as e:
                    return {
                        "success": False,
                        "error": f"解析结果失败: {str(e)}",
                        "raw_output": result.stdout,
                        "stderr": result.stderr
                    }
            else:
                return {
                    "success": False,
                    "error": f"脚本执行失败 (退出码: {result.returncode})",
                    "stderr": result.stderr
                }
                
        except subprocess.TimeoutExpired:
            return {
                "success": False,
                "error": "文件选择超时"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"发生异常: {str(e)}"
            }
    
    def get_info(self) -> Dict[str, Any]:
        """获取选择器信息"""
        return {
            "platform": self.platform,
            "script_path": str(self.script_path),
            "script_exists": self.script_path.exists(),
            "python_version": platform.python_version()
        }


# 创建Flask应用
app = Flask(__name__)
CORS(app)  # 启用CORS支持

# 创建文件选择器实例
try:
    file_selector = CrossPlatformFileSelector()
except FileNotFoundError as e:
    print(f"错误: {e}")
    sys.exit(1)


@app.route('/api/file-selector', methods=['POST', 'OPTIONS'])
def api_file_selector():
    """文件选择器API端点"""
    if request.method == 'OPTIONS':
        response = jsonify({'message': 'OK'})
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS')
        return response
        
    try:
        data = request.get_json() or {}
        
        # 参数验证和默认值
        multiple = data.get('multiple', False)
        file_types = data.get('file_types', None)
        title = data.get('title', '选择文件')
        initial_dir = data.get('initial_dir', None)
        
        # 验证file_types格式 - 现在只支持自定义过滤器格式
        if file_types is not None:
            if not isinstance(file_types, list):
                return jsonify({
                    "success": False,
                    "error": "file_types必须是数组"
                }), 400
                
            # 验证每个过滤器对象的格式
            validated_types = []
            for ft in file_types:
                if isinstance(ft, dict):
                    if 'name' in ft and 'ext' in ft and isinstance(ft['ext'], list):
                        # 确保扩展名以点开头
                        extensions = []
                        for ext in ft['ext']:
                            if isinstance(ext, str):
                                if not ext.startswith('.'):
                                    ext = '.' + ext
                                extensions.append(ext.lower())
                        validated_types.append({
                            'name': ft['name'],
                            'ext': extensions
                        })
                    else:
                        return jsonify({
                            "success": False,
                            "error": "file_types中的每个过滤器必须包含name和ext字段"
                        }), 400
                else:
                    return jsonify({
                        "success": False,
                        "error": "file_types中的每个元素必须是对象，格式：{name: string, ext: string[]}"
                    }), 400
            file_types = validated_types if validated_types else None
        
        # 调用文件选择器
        result = file_selector.select_files(
            multiple=multiple,
            file_types=file_types,
            title=title,
            initial_dir=initial_dir
        )
        
        if result["success"]:
            return jsonify(result)
        else:
            return jsonify(result), 500
            
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"服务器错误: {str(e)}"
        }), 500


if __name__ == '__main__':
    print("🚀 启动跨平台文件选择器服务...")
    print(f"📍 平台: {platform.system()}")
    print(f"🐍 Python版本: {platform.python_version()}")
    print(f"📁 脚本路径: {file_selector.script_path}")
    print("🌐 服务地址: http://localhost:7429")
    
    app.run(host='0.0.0.0', port=7429, debug=False)